package com.gmail.hongyz.myfuse.action;

import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONBuilder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.gmail.hongyz.myfuse.common.Constants;
import com.gmail.hongyz.myfuse.common.PageObject;
import com.gmail.hongyz.myfuse.model.User;
import com.gmail.hongyz.myfuse.service.UserService;
import com.gmail.hongyz.myfuse.util.StringUtils;

public class UserController2 extends MultiActionController {

	private static final Log log = LogFactory.getLog(UserController2.class);
	
	private UserService userService;
	
	public ModelAndView init(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (log.isDebugEnabled()) {
            log.debug("entering 'handleRequest' method...");
        }
		return new ModelAndView("user");
	}
	
	public void query(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (log.isDebugEnabled()) {
            log.debug("entering 'handleRequest' method...");
        }
		PageObject pageObject = PageObject.parseParams(request);
		List<User> users = userService.getUsers(pageObject);
		JSONObject result = new JSONObject();
		JSONArray list = JSONArray.fromObject(users);
		result.accumulate(Constants.EXT_PAGING_TOTAL_COUNT, pageObject.getTotal());
		result.accumulate(Constants.EXT_PAGING_CONTENT, list);
		response.getWriter().println(result.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	public void save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (log.isDebugEnabled()) {
            log.debug("entering 'handleRequest' method...");
        }
		
		String type = request.getParameter("type");
		String userId = request.getParameter("userId");
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		log.debug("name: " + name);
		String email = request.getParameter("email");
		if ("new".equals(type)) {
			User user = new User();
			user.setUserId(userId);
			user.setName(name);
			user.setPassword(password);
			user.setEmail(email);
			log.info("new user: " + user);
			userService.saveUser(user);
		} else {
			User user = userService.getUserByUserId(userId);
			user.setName(name);
			user.setPassword(password);
			user.setEmail(email);
			log.info("edit user: " + user);
			userService.saveUser(user);
		}
		
//		JSONObject result = new JSONObject();
//		response.getWriter().println(result.toString());
//		response.getWriter().flush();
//		response.getWriter().close();
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void saveJson(HttpServletRequest request,
				HttpServletResponse response) throws Exception {
	
			if (log.isDebugEnabled()) {
	            log.debug("entering 'handleRequest' method...");
	        }
			try {
			String type = request.getParameter("type");
			InputStream in = request.getInputStream();
			String jsonData = StringUtils.slurp(in);
			
			JSONObject json = JSONObject.fromObject(jsonData);
			
			String userId = json.getString("userId");
			String name = json.getString("name");
//			String password = json.getString("password");
			log.debug("name: " + name);
			String email = json.getString("email");
			if ("new".equals(type)) {
				User user = new User();
				user.setUserId(userId);
				user.setName(name);
//				user.setPassword(password);
				user.setEmail(email);
				log.info("new user: " + user);
				userService.saveUser(user);
			} else {
				User user = userService.getUserByUserId(userId);
				user.setName(name);
//				user.setPassword(password);
				user.setEmail(email);
				log.info("edit user: " + user);
				userService.saveUser(user);
			}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				throw new RuntimeException(e);
			}
			
			JSONObject result = new JSONObject();
			result.accumulate("result", "OK");
			response.getWriter().println(result.toString());
			response.getWriter().flush();
			response.getWriter().close();
		}
}
